package com.filldream.fastboot.core.manager;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.filldream.fastboot.base.entity.WxConfig;
import com.filldream.fastboot.base.mapper.WxConfigMapper;
import com.filldream.fastboot.base.request.pc.wxconfig.WxConfigListSTO;
import com.filldream.fastboot.common.exception.GlobalException;
import com.filldream.fastboot.common.entity.ErrorCode;
import com.filldream.fastboot.common.entity.P;
import com.filldream.fastboot.common.util.Assert;
import com.filldream.fastboot.common.util.UrlUtil;
import com.filldream.fastboot.core.cache.CacheMap;
import com.filldream.fastboot.core.cache.CacheObj;
import com.filldream.fastboot.core.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author RickSun && iFillDream
 * @version 1.0
 * @data 2020-05-07 18:21
 * @description WxConfigManager
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class WxConfigManager {


    @Resource
    private WxConfigMapper wxConfigMapper;


    //根据appid获取配置
    public WxConfig selectByAppId(String appId) {
        return wxConfigMapper.selectOne(  new LambdaQueryWrapper<WxConfig>().eq(WxConfig::getAppId,appId)  );
    }

    //获取微信配置
    public WxConfig selectById(Long id) {
        CacheObj<WxConfig> cache = CacheUtil.getCache(CacheMap.WX_CONFIG_DETAIL, WxConfig.class, id);
        if(cache.getData() != null ){
            return cache.getData();
        }
        WxConfig serverConfig = wxConfigMapper.selectById(id);
        if(serverConfig == null){
            return null;
        }
        refreshAccessToken(id);
        CacheUtil.cacheObj(cache.getCacheKey(),serverConfig,7120);
        return serverConfig;
    }

    //修改微信配置
    public Integer addWxConfig(WxConfig wxConfig) {
        Integer insertResult = wxConfigMapper.insert(wxConfig);
        return insertResult;
    }

    //修改微信配置
    public Integer updateWxConfig(WxConfig wxConfig) {
        String key = CacheMap.getKey(CacheMap.WX_CONFIG_DETAIL, wxConfig.getId());
        CacheUtil.delKey( key );
        Integer updateStatus = wxConfigMapper.updateById(wxConfig);
        return updateStatus;
    }

    //微信配置列表
    public P<WxConfig> getPageList(WxConfigListSTO wxConfigListSTO){
        QueryWrapper<WxConfig> sql = new QueryWrapper<>();
        sql.orderByAsc( "update_time" );
        sql.orderByDesc("create_time");
//        Long linkId = LoginHolder.getPcUser().getLinkId();
        Long linkId = 0L;
        if( linkId != null && !linkId.equals(0) ){
            sql.eq("link_id",linkId);
        }

        if(StringUtils.isNotBlank(wxConfigListSTO.getAppId())){
            sql.like("appId",wxConfigListSTO.getAppId());
        }
        if(StringUtils.isNotBlank(wxConfigListSTO.getAppSecret())){
            sql.like("appSecret",wxConfigListSTO.getAppSecret());
        }
        if( wxConfigListSTO.getType() != null ){
            sql.eq("type",wxConfigListSTO.getType());
        }


        Page page = wxConfigMapper.selectPage(wxConfigListSTO.page(), sql);


        return P.autoSuccess(page.getTotal(),page.getRecords(),wxConfigListSTO);

    }


    //刷新accessToken
    public WxConfig refreshAccessToken(Long id) {
        WxConfig wxConfig = wxConfigMapper.selectById(id);
        try {
            String result = UrlUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.getAppId()
                    + "&secret=" + wxConfig.getAppSecret());
            JSONObject object = JSONObject.parseObject(result);
            log.info("刷新access_token:{}",object.toString());
            String access_token = object.getString("access_token");
            Assert.isEmpty( access_token,ErrorCode.WECHAT_BASE_ACCESSTOKEN_ERR.reMsg(),object.toString());
            wxConfig.setAccessToken( access_token );
            updateWxConfig(wxConfig);
            CacheObj<WxConfig> cache = CacheUtil.getCache(CacheMap.WX_CONFIG_DETAIL, WxConfig.class, id);
            CacheUtil.cacheObj(cache.getCacheKey(),wxConfig,7120);
            return wxConfig;
        } catch (IOException e) {
            throw new GlobalException(ErrorCode.WECHAT_BASE_ACCESSTOKEN_ERR.reMsg(),e);
        }

    }

    //更新所有配置
    public void refreshAll(){
        List<WxConfig> list = wxConfigMapper.selectList(
                new QueryWrapper<WxConfig>().orderByAsc("update_time")
        );
        list.forEach( e ->{
            refreshAccessToken(e.getId());
        } );
    }

}
